/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODE_SYS_THREAD_POOL_H_
#define NODE_SYS_THREAD_POOL_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <deque>
#include <boost/function.hpp>
#include "node/macros.h"
#include "node/sys/thread.h"
#include "node/sys/event.h"
#include "node/sys/mutex.h"

namespace node {
    namespace sys {

        class ThreadPool
        {
        public:
            const static int MAX_WORKERS = 64;

            struct Task
            {
                void *user_data;
                ::boost::function<void(void)> task;
                ::boost::function<void(void)> complete_callback;
            };

            ThreadPool(void);
            ~ThreadPool(void);

            bool Start(int thread_num);
            void Stop(void);
            void WaitAllTaskCompletedAndStop(void);

            ::node::sys::ThreadPool::Task *NewTask(void);
            void FreeTask(::node::sys::ThreadPool::Task * task);
            bool SubmitTask(::node::sys::ThreadPool::Task *task);

        private:
            class PoolThread : public ::node::sys::Thread
            {
            public:
                PoolThread(::node::sys::ThreadPool &owner);
                virtual ~PoolThread(void);
                virtual void Stop(void);

            protected:
                virtual void Run(void);

            private:
                ::node::sys::ThreadPool &owner_;
            };

            ::node::sys::ThreadPool::Task* GetTask(void);
            bool IsStopping(void) const {
                return stopping_;
            }

            int init_thread_num_;
            int cur_thread_num_;
            volatile bool waiting_for_stop_;
            volatile bool stopping_;
            ::node::sys::Mutex task_queue_lock_;
            ::std::deque<::node::sys::ThreadPool::Task *> task_queue_;
            ::node::sys::Event task_queue_event_;

            ::node::sys::ThreadPool::PoolThread *workers_[MAX_WORKERS];

            DISALLOW_COPY_AND_ASSIGN(ThreadPool);
        };

    }
}

#endif // NODE_SYS_THREAD_POOL_H_
